import router from '@/router'

const modules = import.meta.glob('./views/**/index.vue')

function mapRoutes(routes) {
    return routes.map(route => {
        const r = {
            path: route.path,
            name: route.name,
            component: modules[`./views/${route.component}/index.vue`],
        }
        if (route.children && route.children.length) {
            r.children = mapRoutes(route.children)
        }
        return r
    })
}


// 在 main.js 或 router.beforeEach 里
const localRoutes = localStorage.getItem('routes')
if (localRoutes) {
    const asyncRoutes = mapRoutes(JSON.parse(localRoutes))
    asyncRoutes.forEach(route => {
        // 避免重复注册，可以加个标记
        if (!router.hasRoute(route.name)) {
            router.addRoute(route)
        }
    })
}